import { ResourceDownloaderService } from '../services/resource-downloader.service';
import { ResourceInfo } from '../types/resource.types';

// 测试hash值类型的资源
const testHashResources: ResourceInfo[] = [
  {
    originalUrl: 'Fhx218a1hSHHnJJQ11FsgBGcwLRD',
    localPath: 'resources/other/test/Fhx218a1hSHHnJJQ11FsgBGcwLRD',
    type: 'other' as any,
    source: 'cdn' as any,
    pathInProject: '/Fhx218a1hSHHnJJQ11FsgBGcwLRD'
  },
  {
    originalUrl: 'Fv9W6G12tZzxM-hJjn1phf8vCOb5',
    localPath: 'resources/other/test/Fv9W6G12tZzxM-hJjn1phf8vCOb5',
    type: 'other' as any,
    source: 'cdn' as any,
    pathInProject: '/Fv9W6G12tZzxM-hJjn1phf8vCOb5'
  },
  {
    originalUrl: 'https://cdn.appthen.com/Fp_s_XBf9C1PhnPplQWi0Udx8cw4',
    localPath: 'resources/image/test/Fp_s_XBf9C1PhnPplQWi0Udx8cw4',
    type: 'image' as any,
    source: 'cdn' as any,
    pathInProject: '/Fp_s_XBf9C1PhnPplQWi0Udx8cw4'
  },
  {
    originalUrl: 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js',
    localPath: 'resources/script/test/jweixin-1.6.0.js',
    type: 'script' as any,
    source: 'external' as any,
    pathInProject: '/open/js/jweixin-1.6.0.js'
  }
];

async function testHashDownload() {
  console.log('=== Hash值下载测试 ===\n');

  const fs = require('fs');
  const path = require('path');
  const os = require('os');

  const tempDir = path.join(os.tmpdir(), `hash-test-${Date.now()}`);
  if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir, { recursive: true });
  }

  console.log(`临时目录: ${tempDir}`);

  const downloader = new ResourceDownloaderService();

  try {
    console.log('\n开始下载测试...');
    const result = await downloader.downloadResources(testHashResources, tempDir);

    console.log(`\n=== 下载结果 ===`);
    console.log(`成功: ${result.downloaded.length} 个`);
    console.log(`失败: ${result.failed.length} 个`);

    if (result.downloaded.length > 0) {
      console.log('\n成功下载的文件:');
      result.downloaded.forEach((resource, index) => {
        const fs = require('fs');
        const path = require('path');
        const filePath = path.join(tempDir, resource.localPath);
        const exists = fs.existsSync(filePath);
        const stats = exists ? fs.statSync(filePath) : null;

        console.log(`  ${index + 1}. ${resource.originalUrl}`);
        console.log(`     类型: ${resource.type}`);
        console.log(`     来源: ${resource.source}`);
        console.log(`     大小: ${resource.size || (stats?.size || 0)} bytes`);
        console.log(`     文件存在: ${exists ? '✅' : '❌'}`);
        console.log('');
      });
    }

    if (result.failed.length > 0) {
      console.log('\n失败的文件:');
      result.failed.forEach(({ resource, error }, index) => {
        console.log(`  ${index + 1}. ${resource.originalUrl}`);
        console.log(`     类型: ${resource.type}`);
        console.log(`     来源: ${resource.source}`);
        console.log(`     错误: ${error}`);
        console.log('');
      });
    }

    // 测试URL构建逻辑
    console.log('\n=== URL构建逻辑测试 ===');
    testHashResources.forEach((resource, index) => {
      const isHash = /^[A-Za-z0-9_-]{20,}$/.test(resource.originalUrl);
      const expectedUrl = isHash ? `https://cdn.appthen.com/${resource.originalUrl}` : resource.originalUrl;

      console.log(`${index + 1}. ${resource.originalUrl}`);
      console.log(`   是Hash值: ${isHash ? '✅ 是' : '❌ 否'}`);
      console.log(`   期望URL: ${expectedUrl}`);
      console.log(`   资源类型: ${resource.type}`);
      console.log(`   资源来源: ${resource.source}`);
      console.log('');
    });

    // 清理临时文件
    console.log('\n清理临时文件...');
    const rimraf = require('rimraf');
    rimraf.sync(tempDir);
    console.log('清理完成');

  } catch (error) {
    console.error('测试失败:', error);
  }
}

// 运行测试
if (require.main === module) {
  testHashDownload().catch(console.error);
}

export { testHashDownload };